package com.atguigu.tingshu.payment.strategy.impl;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;


import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.strategy.PaymentStrategy;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;

import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service
@Slf4j
public class OrderPaymentStrategy implements PaymentStrategy {

    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;

    @Autowired
    private WxPayV3Config wxPayV3Config;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Override
    public WeChatPayVo createJsapi(String paymentType, String orderNo) {
        try {
            //根据订单id查询订单数据
            OrderInfo orderInfo = orderInfoFeignClient.getOrderInfo(orderNo).getData();
            if(SystemConstant.ORDER_STATUS_CANCEL.equals(orderInfo.getOrderStatus()))return null ;
            WeChatPayVo weChatPayVo = requestWeChatPay(wxPayV3Config,orderNo,orderInfo.getOrderTitle(),rsaAutoCertificateConfig,userInfoFeignClient);
            //保存交易信息
            paymentInfoService.savePaymentInfo(orderInfo);
            return weChatPayVo;
        }catch (Exception e){
            e.printStackTrace();
            throw new GuiguException(201,"微信支付失败");
        }

    }

    @Override
    public String getPaymentType() {
        return SystemConstant.PAYMENT_TYPE_ORDER;
    }
}
